package server;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import entity.User;
import service.UserServiceImpl;
import utils.ServerConfig;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;

//服务器加入端口号
public class ServerJoin implements Runnable{
    private int port=9990;
    private UserServiceImpl userService;
    private List<ServerOutPut> list=new ArrayList<>();
    private static ServerExit serverExit=null;

    public ServerJoin(UserServiceImpl userService) {
        this.userService=userService;
    }

    static {
        serverExit = new ServerExit(new UserServiceImpl());
        new Thread(serverExit).start();
    }

    @Override
    public void run() {
        User user = new User();
        Random random = new Random();
        ServerSocket serverSocket=null;
        Socket socket=null;
        InputStream inputStream=null;
        ByteOutputStream byteOutputStream=null;
        OutputStream outputStream=null;
        try {
            serverSocket = new ServerSocket(ServerConfig.serverConfig("ServerJoinPort"));
            socket=serverSocket.accept();
            //为加入的用户分配服务端口
            while(true){
                if(port>9995){
                    port=9990;
                }
                if(socket.isClosed()){
                    socket = serverSocket.accept();
                }
                //接收用户发送的用户名
                inputStream = socket.getInputStream();
                byteOutputStream = new ByteOutputStream();
                byte[] bytes = new byte[1024];
                int len;
                while ((len= inputStream.read(bytes))!=-1){
                    byteOutputStream.write(bytes,0,len);
                }

                outputStream = socket.getOutputStream();
                List<User> all = userService.findAlluserport();
//                for(int i=0;i<all.size();i++){
//                    for (User user1: all) {
//                        if(port== user1.getServerport()){
//                            System.out.println(port+"自增");
//                            port++;
//                        }
//                    }
//                }


                //初始化用户信息
                user.setName(byteOutputStream.toString());
                user.setPort(socket.getInetAddress().toString());
                //判断该用户是否是首次登录
                User byPortuserport = userService.findByPortuserport(user.getPort());
                if(byPortuserport==null){
                    //用户为首次登录
                    port++;
                    //分配新的服务端口
                    user.setServerport(port);
                    //保存该用户和分配的服务端号至mysql
                    userService.insertuserport(user);
                    System.out.println(port+"端口被分配");
                    //调用serverOutPut，服务器开启服务端口
                    ServerOutPut serverOutPut = new ServerOutPut(port);
                    Thread thread = new Thread(new ServerOutPut(port));
                    thread.setName(String.valueOf(port));
                    thread.start();
                    list.add(serverOutPut);
                    serverExit.setList(list);
                    outputStream.write(String.valueOf(port).getBytes(StandardCharsets.UTF_8));
                }else {
                    //该用户是二次登录
                    int userport=byPortuserport.getServerport();
                    user.setServerport(userport);
                    //查找mysql中用户保存的服务端口号
                    for (ServerOutPut serverOutPut:list) {
                        if(serverOutPut.getPort()==userport){
                            //调用serverOutPut，启用端口号
                            serverOutPut.setOn(true);
                            System.out.println(userport+"启用");
                            break;
                        }
                    }
                    outputStream.write(String.valueOf(userport).getBytes(StandardCharsets.UTF_8));
                }
                User byPort = userService.findByPort(user.getPort());
                if(byPort== null||!byPort.getName().equals(user.getName())){
                    //将用户信息保存至mysql
                    userService.insert(user);
                }
                outputStream.close();
                byteOutputStream.close();
                inputStream.close();
                //打印加入的用户信息
                System.out.println("Join: "+user.getPort()+"  "+user.getName()+"  "+user.getServerport());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            byteOutputStream.close();
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        Random random = new Random();
//        //port=random.nextInt(8)+9990;
//        DatagramSocket socket = null;
//        User user = new User();
//        try {
//            socket = new DatagramSocket(ServerConfig.serverConfig("ServerJoinPort"));
//        } catch (SocketException e) {
//            e.printStackTrace();
//        }
//        try {
//            while (true){
//                byte[] bytes = new byte[1024];
//                DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
//                socket.receive(packet);
//                //System.out.println(new String(packet.getData(),0, packet.getLength())+""+packet.getAddress());
//                user.setPort(packet.getAddress().toString());
//                user.setName(new String(packet.getData(),0, packet.getLength()));
////                for(int i=0;i<userService.findAll().size();i++){
////                    for (User user1: userService.findAll()) {
////                        if(user1.getServerport()==port){
////                            port++;
////                        }
////                    }
////                }
//                user.setServerport(port);
//                System.out.println("Join=="+user.getPort()+"  "+user.getName()+"  "+user.getServerport());
//                if(userService.findByPort(user.getPort())== null||!userService.findByPort(user.getPort()).getName().equals(user.getName())){
//                    userService.insert(user);
//                }
//                new Thread(new ServerOutPut(port)).start();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally {
//            socket.close();
//        }
    }
}
